package session.stateless;

import entity.ConsolidatedMthSalesFc;
import entity.Employee;
import entity.IndependentVariable;
import entity.Product;
import entity.SalesForecast;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class SalesForecastSessionBean implements SalesForecastSessionBeanLocal {

    @PersistenceContext
    private EntityManager entityManager;
    @EJB
    ProductSessionBeanLocal productSessionBeanLocal;

    @Override
    public void addSalesForecast(Integer salesMonth, Integer salesYear, String salesRepId, String productCode,
            Integer quantity, String remark, String status, Boolean valid) {
        Employee salesRep = entityManager.find(Employee.class, salesRepId);
        Product product = entityManager.find(Product.class, productCode);




        SalesForecast sfc = new SalesForecast(salesMonth, salesYear, salesRep, product, quantity, remark, status, valid);
        entityManager.persist(sfc);
        entityManager.flush();
    }

    @Override
    public void updateSalesForecastStatus(Integer salesYear, Integer salesMonth, String code, String status, Boolean valid) {
        Query query = entityManager.createQuery("SELECT u FROM SalesForecast u WHERE u.salesYear = :inyear AND u.salesMonth=:inMonth");
        query.setParameter("inyear", salesYear);
        query.setParameter("inMonth", salesMonth);

        for (Object o : query.getResultList()) {
            SalesForecast fc = (SalesForecast) o;
            if (fc.getProduct().getCode().compareTo(code) == 0) {
                SalesForecast salesForecast = entityManager.find(SalesForecast.class, fc.getId());
                salesForecast.setStatus(status);
                salesForecast.setValid(valid);
                entityManager.persist(salesForecast);
                entityManager.flush();
            }

        }
    }

    @Override
    public void updateSalesForecastStatus(Integer salesYear, Integer salesMonth, String status, Boolean valid) {

        Query query = entityManager.createQuery("SELECT u FROM SalesForecast u WHERE u.salesYear = :inyear AND u.salesMonth=:inMonth");
        query.setParameter("inyear", salesYear);
        query.setParameter("inMonth", salesMonth);

        for (Object o : query.getResultList()) {
            SalesForecast fc = (SalesForecast) o;
            SalesForecast salesForecast = entityManager.find(SalesForecast.class, fc.getId());
            salesForecast.setStatus(status);
            salesForecast.setValid(valid);
            entityManager.persist(salesForecast);
            entityManager.flush();

        }

    }

    @Override
    public ArrayList<SalesForecast> getSalesForecasts(Integer salesYear, String code) {

        Query query = entityManager.createQuery("SELECT u FROM SalesForecast u WHERE u.salesYear = :inyear");
        query.setParameter("inyear", salesYear);

        ArrayList<SalesForecast> fcs = new ArrayList<SalesForecast>();

        for (Object o : query.getResultList()) {
            SalesForecast fc = (SalesForecast) o;
            if (fc.getProduct().getCode().compareTo(code) == 0) {
                fcs.add(fc);
            }
        }

        return fcs;

    }

    @Override
    public void removeSalesForecast(Long id) {
        SalesForecast fc = entityManager.find(SalesForecast.class, id);
        entityManager.remove(fc);
        entityManager.flush();
    }

    @Override
    public void addSalesForecasts(ArrayList<SalesForecast> salesForecasts, String currentYear, String code) {
        ArrayList<SalesForecast> oldSalesForecasts = getSalesForecasts(Integer.parseInt(currentYear), code);

        for (SalesForecast sfc : oldSalesForecasts) {
            removeSalesForecast(sfc.getId());
        }

        for (SalesForecast sfc : salesForecasts) {



            addSalesForecast(sfc.getSalesMonth(), sfc.getSalesYear(), sfc.getSalesRep().getUserId(), sfc.getProduct().getCode(),
                    sfc.getQuantity(), sfc.getRemark(), sfc.getStatus(), sfc.getValid());
            try {
            } catch (Exception ex) {
                System.out.println(ex.toString());
            }
        }
    }

    @Override
    public ArrayList<IndependentVariable> getIndependentVariables(String filepath) {
        ArrayList<IndependentVariable> independentVariables = new ArrayList<IndependentVariable>();
        IndependentVariable independentVariable;

        try {
            FileReader fr = new FileReader(filepath);
            BufferedReader br = new BufferedReader(fr);
            String s;
            while ((s = br.readLine()) != null) {
                String[] temp = s.split(",");
                String[] date_temp = temp[0].split("-");

                independentVariable = new IndependentVariable(Integer.parseInt(date_temp[1]), Integer.parseInt(date_temp[2]), Double.parseDouble(temp[1]));
                independentVariables.add(independentVariable);
            }
            fr.close();
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        return independentVariables;
    }

    @Override
    public ArrayList<SalesForecast> getSalesForecasts(String status) {
        Query query = entityManager.createQuery("SELECT u FROM SalesForecast u WHERE u.status = :instatus");
        query.setParameter("instatus", status);

        ArrayList<SalesForecast> fcs = new ArrayList<SalesForecast>();

        for (Object o : query.getResultList()) {
            SalesForecast fc = (SalesForecast) o;

            fcs.add(fc);

        }

        return fcs;


    }

    @Override
    public ArrayList<ConsolidatedMthSalesFc> getConsolidatedMontlySalesForecast(Integer forecastYear) {
        ArrayList<ConsolidatedMthSalesFc> consolidatedMthSalesFcs = new ArrayList<ConsolidatedMthSalesFc>();

        Query query = entityManager.createQuery("SELECT u FROM SalesForecast u WHERE u.salesYear = :inyear");
        query.setParameter("inyear", forecastYear);

        ArrayList<SalesForecast> salesForecasts = new ArrayList<SalesForecast>();

        for (Object o : query.getResultList()) {
            SalesForecast fc = (SalesForecast) o;
            if (fc.getValid())
            salesForecasts.add(fc);
        }

        for (SalesForecast salesForecast : salesForecasts) {


            Boolean found = false;
            for (ConsolidatedMthSalesFc cmsfc : consolidatedMthSalesFcs) {
                if (salesForecast.getSalesMonth().compareTo(cmsfc.getSalesMonth()) == 0 && salesForecast.getSalesYear().compareTo(cmsfc.getSalesYear()) == 0) {
                    //add fc of the product into the respective mth and year
                    found = true;
                    cmsfc.getSalesForecasts().add(salesForecast);


                }
            }
            if (!found) {
                //create a new mth and year
                ConsolidatedMthSalesFc consolidatedMthSalesFc = new ConsolidatedMthSalesFc(salesForecast.getSalesMonth(), salesForecast.getSalesYear(), new ArrayList<SalesForecast>());
                consolidatedMthSalesFc.getSalesForecasts().add(salesForecast);
                consolidatedMthSalesFc.setStatus(salesForecast.getStatus());
                consolidatedMthSalesFcs.add(consolidatedMthSalesFc);


            }


        }

        ArrayList<Product> products = new ArrayList(productSessionBeanLocal.getProducts());

        for (ConsolidatedMthSalesFc confc : consolidatedMthSalesFcs) {
            ArrayList<SalesForecast> tempAlSalesFc = new ArrayList(confc.getSalesForecasts());
            Collections.sort(tempAlSalesFc);
            confc.setSalesForecasts(tempAlSalesFc);
            confc.setCompleted(tempAlSalesFc.size() + "/" + products.size());
        }
        return consolidatedMthSalesFcs;

    }
    
//    @Override
//    public ArrayList <SalesForecast> getAdjustedSalesForecasts (Integer salesYear, Integer salesMonth, String status)
//    {
//        ArrayList <SalesForecast> salesForecasts = new ArrayList<SalesForecast> ();
//        for (SalesForecast sfc:getSalesForecasts(status) )
//        {
//            if (sfc.getSalesMonth().compareTo(salesMonth) ==0 && sfc.getSalesYear().compareTo(salesYear)==0)
//                salesForecasts.add(sfc);
//        }
//        return salesForecasts;
//    }
}
